<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="农场名称" prop="name">
        <el-select
          v-model="farmTourValue"
          placeholder="请选择农场"
          class="!w-240px"
          style="margin-right: 10px;"
          @change="handleFarmChange"
        >
          <el-option
            v-for="item in farmTourList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="时间" prop="timeRange">
        <el-date-picker
          v-model="queryParams.timeRange"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>

      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
      </el-form-item>
    </el-form>

    <div class="expend-box">
      <el-row :gutter="20">
        <el-col :span="24">
          <div class="box-radio">
            <span style="margin-right: 10px;">数据类型:</span>
            <el-radio-group v-model="selectedDataType" @change="handleDataTypeChange">
              <el-radio value="温度">温度</el-radio>
              <el-radio value="其他数据">其他数据</el-radio>
            </el-radio-group>
          </div>
        </el-col>
        <el-col :span="24">
          <div>
            <span style="margin-right: 10px;">展示类型:</span>
            <el-checkbox-group v-model="selectedOptions" @change="handleOptionsChange">
              <el-checkbox v-for="item in currentOptions" :key="item" :value="item">{{ item }}</el-checkbox>
            </el-checkbox-group>
          </div>
        </el-col>
        <el-col :span="24">
          <div>
            <span style="margin-right: 10px;">农舍名称:</span>
            <el-checkbox-group v-model="selectedFarmhouses" @change="handleHouseChange">
              <el-checkbox
                v-for="(item, index) in farmList"
                :key="index"
                :value="item.id"
              >
                {{ item.houseName }}
              </el-checkbox>
            </el-checkbox-group>
          </div>
        </el-col>
      </el-row>
    </div>
    <div class="expend-echarts">
      <!-- 分隔线 -->
      <el-divider />
      <div style="margin:20px" v-loading="loading" element-loading-text="努力加载中...">
        <div id="chart" ref="chartRef" style="width: 100%; height: 600px;"></div>
      </div>
    </div>
  </ContentWrap>
</template>

<script setup lang="ts">
import { debounce } from 'lodash';
import { FarmTourApi, FarmTourVO } from '@/api/farmTour/index';
import { FarmWarnApi } from '@/api/farmTour/warn/index';
// import { ECAApi } from '@/api/houseTour/ECA/index';
import { farmTourEnv } from '@/api/farmTour/envContrast/index';
import { EChartsType, EChartsOption } from 'echarts';
import { onMounted, ref, reactive, watch } from 'vue';
import * as echarts from "echarts";

defineOptions({ name: 'ECA' });

const farmList = ref([]); // 用于存储农舍列表
const selectedFarmhouses = ref([]); // 用于存储用户选择的农舍ID
const loading = ref(true);
const farmTourValue = ref<any>(null);
const farmTourList = ref<FarmTourVO[]>([]);

const queryParams = reactive({
  name: undefined,
  createTime: [],
  farmHouseId: undefined,
  timeRange: []
});

interface WeatherDataVo {
  farmHouseId: number;
  boardTemps: number[][];
  outdoorTemperature: number[];
  interTemperature: number[];
  createTime: string[];
}

const chartRef = ref(null);
const myChart = ref<EChartsType | null>(null);
const weatherData = ref<WeatherDataVo[]>([]); // 用于存储所有农舍的温度数据
const processedDataStore = ref({}); // 用于存储所有农舍的其他处理数据
const labels = ref<string[]>([]); // 用于存储时间标签

const dataTypes = {
  温度: [
    '主板温度1', '主板温度2', '主板温度3', '主板温度4', '主板温度5', '主板温度6', '主板温度7', '主板温度8',
    '负板温度1', '负板温度2', '负板温度3', '负板温度4', '负板温度5', '负板温度6', '负板温度7', '负板温度8',
    '室外温度', '室内温度','目标温度'
  ],
  其他数据: [ '通风级别', 'NH3浓度', 'CO2浓度', '负压', '湿度']
};

const selectedDataType = ref('温度'); // 默认选择温度
const selectedOptions = ref(['主板温度1']); // 默认选中 '温度1'
const currentOptions = ref(dataTypes.温度); // 初始显示温度选项
const farmHouseMapping = ref({}); // 创建映射对象
// 获取农场列表
const getList = async () => {
  loading.value = true;
  try {
    const res = await FarmTourApi.getFarmTour();
    if (res) {
      farmTourList.value = res;
      // 设置默认选择为第一个农场
      if (farmTourList.value.length > 0) {
        farmTourValue.value = farmTourList.value[0].id;
        await getHouseList(farmTourValue.value);
      }
    }
  } catch (error) {
    console.log(error, 'error');
  } finally {
    loading.value = false;
  }
};

// 获取农舍列表
// const getHouseList = async (selectedFarmID) => {
//   const res = await FarmWarnApi.getFarmHouseApi({ farmId: selectedFarmID });
//   if (res) {
//     farmList.value = res;
//      // 默认选择第一个农舍
//     if (farmList.value.length > 0) {
//       selectedFarmhouses.value = [farmList.value[0].id]; // 设置为第一个农舍的 ID
//       await getECAData(selectedFarmhouses.value); // 获取数据
//     } else {
//       selectedFarmhouses.value = []; // 如果没有农舍，清空选择
//     }
//   }
// };
const getHouseList = async (selectedFarmID) => {
  const res = await FarmWarnApi.getFarmHouseApi({ farmId: selectedFarmID });
  if (res) {
    farmList.value = res;
    // 默认选择第一个农舍
    if (farmList.value.length > 0) {
      selectedFarmhouses.value = [farmList.value[0].id]; // 设置为第一个农舍的 ID
      await getECAData(selectedFarmhouses.value); // 获取数据
    } else {
      selectedFarmhouses.value = []; // 如果没有农舍，清空选择
      weatherData.value = []; // 清空温度数据
      labels.value = []; // 清空时间标签
      initChart(); // 重新初始化图表，确保不显示上一个农场的图表
    }
  }
};

// 获取ECA数据
// const getECAData = async (farmHouseIds) => {
//   loading.value = true;
//   const typeMapping = {
//     温度: 1,
//     其他数据: 2
//   };
//   const type = typeMapping[selectedDataType.value];
  
//   try {
//     const params = {
//       farmHouseId: farmHouseIds,
//       type: type,
//       createTime: queryParams.timeRange.length === 2 ? queryParams.timeRange : undefined
//     };
//     const res = await farmTourEnv.getFarmTourEnvApi(params);
//     if (res) {
//       if (type === 1) {
//         processWeatherData(res); // 处理温度数据
//       } else if (type === 2) {
//         processOtherData(res); // 处理其他数据
//       }
//     } else {
//       console.error('数据格式错误或无数据', res);
//     }
//   } catch (error) {
//     console.log(error);
//   } finally {
//     loading.value = false;
//   }
// };
const getECAData = async (farmHouseIds) => {
  loading.value = true;
  const typeMapping = {
    温度: 1,
    其他数据: 2
  };
  const type = typeMapping[selectedDataType.value];

  // 在请求开始前清空上一个图表的数据
  weatherData.value = []; // 清空温度数据
  processedDataStore.value = {}; // 清空处理后的数据
  labels.value = []; // 清空时间标签

  try {
    const params = {
      farmHouseId: farmHouseIds,
      type: type,
      createTime: queryParams.timeRange.length === 2 ? queryParams.timeRange : undefined
    };
    const res = await farmTourEnv.getFarmTourEnvApi(params);
    if (res) {
      if (type === 1) {
        processWeatherData(res); // 处理温度数据
      } else if (type === 2) {
        processOtherData(res); // 处理其他数据
      }
    } else {
      console.error('数据格式错误或无数据', res);
    }
  } catch (error) {
    console.log(error);
  } finally {
    loading.value = false;
  }
};

// 处理ECA的温度数据
const processWeatherData = (data) => {
    weatherData.value = [];
    labels.value = [];

    Object.keys(data).forEach(farmHouseId => {
        const farmHouseData = data[farmHouseId];
        const boardTemps = {
            farmHouseId: farmHouseId,
            boardTemps: [[], [], [], [], [], [], [], []], // 主板温度数组
            assistanTemp: [[], [], [], [], [], [], [], []], // 负板温度数组
            outdoorTemperature: [],
            interTemperature: [],
            targetTemperature: [], // 添加目标温度
            createTime: []
        };

        farmHouseData.forEach(item => {
            for (let i = 1; i <= 8; i++) {
                boardTemps.boardTemps[i - 1].push(item[`boardTemp${i}`] || 0);
                boardTemps.assistanTemp[i - 1].push(item[`assistanTemp${i}`] || 0);
            }
            boardTemps.outdoorTemperature.push(item.outdoorTemperature || 0);
            boardTemps.interTemperature.push(item.interTemperature || 0);
            boardTemps.targetTemperature.push(item.stemperature || 0); // 添加目标温度
            boardTemps.createTime.push(new Date(item.createTime));
        });

        weatherData.value.push(boardTemps);

        // 生成时间标签
        const labelsForFarmHouse = farmHouseData.map(item => {
            return new Date(item.createTime).toLocaleString();
        });
        labels.value = [...new Set([...labels.value, ...labelsForFarmHouse])];
    });

    initChart();
};

// 初始化温度图表
const initChart = () => {
    const series = [];

    selectedOptions.value.forEach(option => {
        weatherData.value.forEach(dataItem => {
            if (dataItem && selectedDataType.value === '温度') {
                // 主板温度
                if (option.startsWith('主板温度')) {
                    const index = parseInt(option.replace('主板温度', '')) - 1;
                    if (dataItem.boardTemps && dataItem.boardTemps[index]) {
                        series.push({
                            name: `${option} - 农舍名称: ${dataItem.farmHouseId}`,
                            type: 'line',
                            data: dataItem.boardTemps[index],
                            tooltip: {
                                valueFormatter: (value) => `${value} °C`,
                            },
                        });
                    }
                }
                // 负板温度
                else if (option.startsWith('负板温度')) {
                    const index = parseInt(option.replace('负板温度', '')) - 1;
                    if (dataItem.assistanTemp && dataItem.assistanTemp[index]) {
                        series.push({
                            name: `${option} - 农舍名称: ${dataItem.farmHouseId}`,
                            type: 'line',
                            data: dataItem.assistanTemp[index],
                            tooltip: {
                                valueFormatter: (value) => `${value} °C`,
                            },
                        });
                    }
                }
                // 室外温度
                else if (option === '室外温度') {
                    series.push({
                        name: `${option} - 农舍ID: ${dataItem.farmHouseId}`,
                        type: 'line',
                        data: dataItem.outdoorTemperature,
                        tooltip: {
                            valueFormatter: (value) => `${value} °C`,
                        },
                    });
                }
                // 室内温度
                else if (option === '室内温度') {
                    series.push({
                        name: `${option} - 农舍ID: ${dataItem.farmHouseId}`,
                        type: 'line',
                        data: dataItem.interTemperature,
                        tooltip: {
                            valueFormatter: (value) => `${value} °C`,
                        },
                    });
                }
                // 目标温度
                else if (option === '目标温度') {
                    series.push({
                        name: `${option} - 农舍ID: ${dataItem.farmHouseId}`,
                        type: 'line',
                        data: dataItem.targetTemperature,
                        tooltip: {
                            valueFormatter: (value) => `${value} °C`,
                        },
                    });
                }
            }
        });
    });

    // 生成图表配置
    const option: EChartsOption = {
        tooltip: {
            trigger: 'item',
            axisPointer: {
                type: 'cross',
                crossStyle: {
                    color: '#999'
                }
            },
            formatter: (params) => {
                return `${params.seriesName}: ${params.value}`;
            }
        },
        legend: {
            data: series.map(s => s.name),
        },
        xAxis: {
            type: 'category',
            data: labels.value,
        },
        yAxis: {
            type: 'value',
            axisLabel: {
                formatter: (value) => `${value} °C`,
            },
        },
        series: series,
    };

    // 更新图表
    if (myChart.value) {
        myChart.value.clear();
        myChart.value.setOption(option);
    } else {
        myChart.value = echarts.init(chartRef.value);
        myChart.value.setOption(option);
    }
};
const handleOptionsChange = () => {
    if (selectedDataType.value === '其他数据') {
      initChartForOtherData(); // 重新获取数据
    } else {
        initChart(); // 如果是温度数据，则按原逻辑初始化
    }
};


const processOtherData = (data) => {
    const processedData = {};

    // 遍历返回的数据
    Object.keys(data).forEach(farmHouseId => {
        const farmHouseData = data[farmHouseId];

        // 初始化每个农舍的数据结构
        processedData[farmHouseId] = {
            pulseWindSpeed: [],
            pulseWindLevel: [],
            nh3Concentration: [],
            co2Concentration: [],
            interPressure: [],
            airHumidity: [],
            createTime: []
        };

        // 遍历每个设备的数据
        farmHouseData.forEach(item => {
            processedData[farmHouseId].pulseWindSpeed.push(item.pulseWindSpeed || 0);
            processedData[farmHouseId].pulseWindLevel.push(item.pulseWindLevel || 0);
            processedData[farmHouseId].nh3Concentration.push(item.nh3Concentration || 0);
            processedData[farmHouseId].co2Concentration.push(item.co2Concentration || 0);
            processedData[farmHouseId].interPressure.push(item.interPressure || 0);
            processedData[farmHouseId].airHumidity.push(item.airHumidity || 0);
            processedData[farmHouseId].createTime.push(new Date(item.createTime).toLocaleString());
        });
    });

    processedDataStore.value = processedData; // 保存处理后的数据
    initChartForOtherData(processedData); // 初始化图表
};

// 初始化其他数据的图表
const initChartForOtherData = () => {
    const series = [];

    // 生成时间标签（假设所有农舍的 createTime 数组长度相同）
    const firstFarmHouseId = Object.keys(processedDataStore.value)[0];
    const labels = processedDataStore.value[firstFarmHouseId].createTime;

    // 根据所选的展示类型生成数据系列
    selectedOptions.value.forEach(option => {
        Object.keys(processedDataStore.value).forEach(farmHouseId => {
            if (option === '风速') {
                series.push({
                    name: `风速 - 农舍: ${farmHouseId}`,
                    type: 'line',
                    data: processedDataStore.value[farmHouseId].pulseWindSpeed,
                    tooltip: {
                        valueFormatter: (value) => `${value} m/s`,
                    },
                });
            } else if (option === '通风级别') {
                series.push({
                    name: `通风级别 - 农舍: ${farmHouseId}`,
                    type: 'line',
                    data: processedDataStore.value[farmHouseId].pulseWindLevel,
                    tooltip: {
                        valueFormatter: (value) => `${value}`,
                    },
                });
            } else if (option === 'NH3浓度') {
                series.push({
                    name: `NH3浓度 - 农舍: ${farmHouseId}`,
                    type: 'line',
                    data: processedDataStore.value[farmHouseId].nh3Concentration,
                    tooltip: {
                        valueFormatter: (value) => `${value} ppm`,
                    },
                });
            } else if (option === 'CO2浓度') {
                series.push({
                    name: `CO2浓度 - 农舍: ${farmHouseId}`,
                    type: 'line',
                    data: processedDataStore.value[farmHouseId].co2Concentration,
                    tooltip: {
                        valueFormatter: (value) => `${value} ppm`,
                    },
                });
            } else if (option === '负压') {
                series.push({
                    name: `负压 - 农舍: ${farmHouseId}`,
                    type: 'line',
                    data: processedDataStore.value[farmHouseId].interPressure,
                    tooltip: {
                        valueFormatter: (value) => `${value} Pa`,
                    },
                });
            } else if (option === '湿度') {
                series.push({
                    name: `湿度 - 农舍: ${farmHouseId}`,
                    type: 'line',
                    data: processedDataStore.value[farmHouseId].airHumidity,
                    tooltip: {
                        valueFormatter: (value) => `${value} %`,
                    },
                });
            }
        });
    });

    // 生成图表配置
    const option: EChartsOption = {
        tooltip: {
            trigger: 'item',
            axisPointer: {
                type: 'cross',
                crossStyle: {
                    color: '#999'
                }
            },
            formatter: (params) => {
                return `${params.seriesName}: ${params.value}`;
            }
        },
        legend: {
            data: series.map(s => s.name),
        },
        xAxis: {
            type: 'category',
            data: labels,
        },
        yAxis: {
            type: 'value',
            axisLabel: {
                formatter: (value) => `${value}`,
            },
        },
        series: series,
    };

    // 更新图表
    if (myChart.value) {
        myChart.value.clear();
        myChart.value.setOption(option);
    } else {
        myChart.value = echarts.init(chartRef.value);
        myChart.value.setOption(option);
    }
};


// 处理数据类型切换
const handleDataTypeChange = () => {
  currentOptions.value = dataTypes[selectedDataType.value];
  selectedOptions.value = [currentOptions.value[0]];
  getECAData(selectedFarmhouses.value);
};

// 处理农舍选择变化
const handleFarmChange =async  () => {
  await getHouseList(farmTourValue.value); // 获取新的农舍数据
};

const handleHouseChange = () => {
  getECAData(selectedFarmhouses.value);
};
// 查询数据
const handleQuery = async () => {
  if (queryParams.timeRange.length === 2) {
    await getECAData(selectedFarmhouses.value);
  } else {
    console.warn("请选择完整的时间范围！");
  }
};

// 重置查询
const resetQuery = () => {
  queryParams.timeRange = [];
  getList();
  queryFormRef.value.resetFields();
  selectedFarmhouses.value = [];
  handleQuery();
};

// 监听选中项目的变化
watch(selectedOptions, () => {
  initChart();
});

// 初始化
onMounted(() => {
  getList();
});
</script>

<style scoped lang="scss">
.expend-box {
  margin: 10px 10px;
  padding: 10px;
  background-color: rgba(239, 246, 255, 0.996078431372549);
}
</style>
